﻿package 
{

	import com.element.role.Man;
	import com.map.ShowObjectContain;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.ApplicationDomain;
	import flash.geom.Point;
	import flash.utils.getDefinitionByName;
	
	import com.event.EventZheng;
	
	import com.staticInfo.*;
	
	import com.utils.*
	
	import com.map.Map;
	
	import com.controller.MapController;
	
	import com.model.MapDataManage;
	import com.model.MainData;
	
	import com.element.movieClip.*;
	import com.element.*
	import com.socket.LocalCommunications;
	
	
	/**
	 * ...
	 * @author zhengzihua
	 */
	public class Main extends Sprite 
	{
		public static var mainStage:Sprite;//表示游戏区域的sprit
		
		private var initLoadArr:Array;//初始化游戏需要导入的素材
		
		private var bottomBar:BottomBar;
		private var topBar:TopBar;
		
		private var mapContain:Sprite;//地图容器
		private var showObjectContain:ShowObjectContain;//物体
		private var map:Map;//tiles,gridFarm;
		private var role:Man;//角色
		
		private var mainData:MainData = new MainData ();
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			//导入素材
			//stage.stageFocusRect = false;//不显示focus黄色边框
			
			initLoadArr = new Array();
			initLoadArr.push(LoadUrl.lib_main);
			initLoadArr.push(LoadUrl.lib_shop);
			
			var initLoad:BatchLoad = new BatchLoad(initLoadArr,"same");//同一个域
			initLoad.load();
			initLoad.addEventListener(EventConst.EVENT_LOADCOMPLETE, onLoadComplete);
		}
		
		private function onLoadComplete(e:Event):void 
		{
			DebugTrace.dtrace("导入完成。");
			var thisLoad:BatchLoad = e.currentTarget as BatchLoad;
			thisLoad.removeEventListener(EventConst.EVENT_LOADCOMPLETE, onLoadComplete);
			thisLoad = null;
			
			//LocalCommunications.LocalCommInit();
			//LocalCommunications.dispather.addEventListener(EventConst.EVENT_FROMSERVER, farmDeal);
			
			putMainStage();
			putMap();
			putShowObject();
			putRole();
			
			topBar = new TopBar();
			addChild(topBar);
			topBar.showUserInfo("wssmrw", 20, 19898);
			
			bottomBar = new BottomBar();
			addChild(bottomBar);
			bottomBar.y = 540;
			//mainData
			addEventListener(EventConst.EVENT_CHANGEOPERATE, onChangeOperate);//operate变化第一阶段
			mainData.addEventListener(EventConst.EVENT_LOGIN, onLogin);
			mainData.addEventListener(EventConst.EVENT_CHANGEOPERATE, onChangeOperate)//检测operate值的变化
		}
		private function putMainStage():void{
			//游戏场景
			mainStage = new Sprite();
			mainStage.name="mainStage"
			mainStage.x = MapData.mapInitX;
			mainStage.y = MapData.mapInitY;
			addChild(mainStage);
		}
		private function putMap():void {
			//地图
			var mapDataManege:MapDataManage = new MapDataManage();
			var mapController:MapController = new MapController(mapDataManege);
			map= new Map(mapController,mapDataManege);
			map.drawMap(30, 30);
			//mapContain.addEventListener(EventConst.EVENT_SEEKROAD, onSeekRoad);//找到路径
			mainStage.addEventListener(EventConst.EVENT_MAP_MAIN, onMapToMain);//更改目标点
			mainStage.addChild(map);
			//mainStage.addChild(map.showObjectContain);
			mainStage.addEventListener(EventConst.EVENT_CLIPMENU_MAIN, onClipMenuEvent);
		}
		private function putRole():void {
			//role
			role = new Man();
			role.x = MapData.roleInitP.x;//初始化位置
			role.y = MapData.roleInitP.y;
			role.manPoint = MapData.roleInitP;
			role.cacheAsBitmap = true;
			//map.role = role;
			showObjectContain.addObj(role);
		}
		private function putShowObject():void {
			showObjectContain = new ShowObjectContain();
			mainStage.addChild(showObjectContain);
		}
		/**
		 * logoin信息改变时
		 * @param	e
		 */
		private function onLogin(e:Event):void 
		{
			
		}
		//监测对mainDAta.operate的修改,该值的修改过程分为三个阶段,
		//第一阶段:点击图标,图标发送事件信息到stage,在该方法中处理完后修改mainData.operate的值
		//第二阶段:mainData收到值的修改后,发送第二阶段的信息,以便于结束上一个操作的状态,操作完成后发送事件信息给mainData
		//第三阶段:mainData发送第三阶段的事件信息,收到该信息后,处理operate值改变之后的操作
		private function onChangeOperate(e:EventZheng):void 
		{
			var phase:int = e.obj.phase;
			var eventType:String = e.obj.type;
			DebugTrace.dtrace("code info Main.as:changeOperate阶段为" + phase);
			DebugTrace.dtrace("code info Main.as:changeOperate类型为" + e.obj.type);
			switch(phase) {
				case 1:
					mainData.operate = eventType;
					switch(eventType) {
						case "road":
							break;
						case "put":
							var	clip:Clips = ObjectList.mappingData(e.obj.clipStr);
							mainData.putObjType = e.obj.clipStr;//摆放在地图上物体的类型
							map.siteNum = new Point(clip.row, clip.cols);//该数据用于map中checkPut
							clip = null;
							break;
						default:
							break;
					}
					break;
				case 2:
					switch(eventType) {
						case "road":
							break;
						case "put":
							map.mapDataManage.allowSite = false;
							break;
						case "shop":
							//关闭shop
							break;
						default:
							break;
					}
					mainData.dispatchEvent(new EventZheng(EventConst.EVENT_READYED));
					break;
				case 3:
					switch(eventType) {
						case "road":
							break;
						case "put":
							map.mapDataManage.allowSite = true;
							break;
						case "shop":
							//打开shop
							break;
						default:
							break;
					}
					break;
				default:
					break;
			}	
		}
		/**
		 * clipMenu上的按钮点击之后的处理
		 * @param	e
		 */
		private function onClipMenuEvent(e:EventZheng):void 
		{
			var t:String = e.obj.type;
			switch(t) {
				case "clipClick":
					var clip:Clips = e.obj.clip;
					if (clip is IShowMenu) {
						IShowMenu(clip).showMenu();
					}
					break;
				case "move":
					//move物体，需要先记下物体的操作，等移动完成之后，再恢复回去
					moveObj();
					//mainData.putObjType=delObj(e);
					//mainData.operate = "put";
					break;
				case "del":
					delObj(e);
					break;
				case "dirAngle":
					//如果不是正方形，在转换之前需要检查新的tile是否能够放置物体
					changeDirection(e);
					break;
				default:
					break;
			}
		}
		/**
		 * 摆放物体
		 * @param	sp	起点
		 * @param	clipStr	摆放物体的编号
		 */
		private function putObj(sp:Point, clipStr:String):void {
			var clip:Clips = ObjectList.mappingData(clipStr);
			var isSpecialDeal:Boolean = false;
			if (clip.row == clip.obstacleRow && clip.cols == clip.obstacleCols) {//占位，改地图上的设置都是一样的
				isSpecialDeal=false;
			}else {
				isSpecialDeal = true;
			}
			var siteRow:int = clip.row;
			var siteCols:int = clip.cols;
			var obstacleRow:int = clip.obstacleRow;
			var obstacleCols:int = clip.obstacleCols;
			if (map.checkPut(sp,siteRow,siteCols)) {
				showObjectContain.putElement(sp, siteRow, siteCols, clip);
				if (isSpecialDeal) {
					//暂时不做处理，等需求下来后在修改，这个方法不会被执行
					//map.putElement(new Point(sp.x+1,sp.y+1), obstacleRow, obstacleCols, role);
				}else{
					map.putElement(sp, siteRow, siteCols, role);
				}
			}else {
				DebugTrace.dtrace("code info Main.as:不能摆放物体");
			}
			var p:Point = TransformCoordinate.transformCoor(sp);
			clip.x = p.x;
			clip.y = p.y;
		}
		private function moveObj():void {
			
		}
		//删除地图上的物体，分三步操作
		//1.置回map中的值
		//2.删除showObjecContain中的显示对象
		//3.返回删除的对象
		private function delObj(e:EventZheng ):String {
			var clip:Clips = e.obj.clip;
			var sp:Point = new Point(clip.sx,clip.sy);
			var row:int = clip.row;
			var cols:int = clip.cols;
			var level:int = clip.level;
			map.changeC(sp, row, cols, 0);
			showObjectContain.delObj(level);
			
			return clip.listNum;
		}
		private function changeDirection(e:EventZheng):void {
			var clip:Clips = e.obj.clip;
			var row:int = clip.row;
			var cols:int = clip.cols;
			var sp:Point = new Point(clip.sx, clip.sy);
			map.changeC(sp, row, cols, 0);
			clip.row = cols;
			clip.cols = row;
			map.changeC(sp, clip.row , clip.cols, 1);
			clip.directionAng++;
		}
		/**
		 * 收到map发送给Main的信息
		 * @param	e
		 */
		private function onMapToMain(e:EventZheng):void 
		{
			var t:String = e.obj.type;
			switch(t) {
				case "tileClick":
					onTileClick(e);
					break;	
				case "seekRoad":
					onSeekRoad(e);
					break
			}
		}
		/**
		 * 鼠标在地图上点击后，进行以下操作
		 * 寻径
		 * 摆放物体
		 * @param	e
		 */
		private function onTileClick(e:EventZheng):void 
		{
			
			var tp:Point = e.obj.point;
			var operate:String = mainData.operate;
			switch(operate) {
				case "road":
					var expenseTime:ExpenseTime = new ExpenseTime("寻路");
					map.seekRoad(role.manPoint,tp);
					expenseTime.endTime();
					expenseTime = null;
					break;
				case "put":
					//摆放物体
					putObj(tp,mainData.putObjType);
					break;
				default:
					break;
			}
		}

		private function onSeekRoad(e:EventZheng):void//走路
		{
			var path:Array = e.obj.roadPath;
			var lineArr:Array = path.slice(0);
			addChild(DrawLine.drawLine(lineArr,role));
			if (path.length == 0) {
				DebugTrace.dtrace("code error Main.as:死路一条.");
				role.animal_stopWalk();
				return;
			}
			role.walkRoad(path);
		}
		//处理从服务器端传送过来的信息
		private function farmDeal(e:EventZheng):void {
			var cmds:Object = { };
			cmds = ExplainData.explainData(e.obj.str);
			switch(cmds.type) {
				case "login":
					if (cmds.info == "suc") {
						mainData.loginStatus = true;
					}else if(cmds.info=="error"){
						mainData.loginStatus = false;
						DebugTrace.dtrace("code erro Main.as:" + cmds.status);
					}
					break;
				case "mapData":
					var obstacleArr:Array = [];
					var numMapData:int = 0;
					obstacleArr = cmds.info.split(",");
					numMapData = obstacleArr.length;
					for (var iMapData:int = 0; iMapData < numMapData; iMapData++ ) {
						obstacleArr[iMapData]=obstacleArr[iMapData].split(";")
					}
					for (var iMapData2:int = 0; iMapData2 < numMapData; iMapData2++ ) {
						map.c[obstacleArr[iMapData2][0]][obstacleArr[iMapData2][1]] = 1;
					}
					break;
				case "thingsData":
					var thingsDataArr:Array = [];
					var numThingsData:int = 0;
					thingsDataArr = cmds.info(",");
					numThingsData = thingsDataArr.length;
					for (var iThingsData:int; iThingsData < numThingsData; iThingsData++ ) {
						thingsDataArr[iThingsData]=thingsDataArr[iThingsData].split(";")
					}
					for (var iThingsData2:int; iThingsData2 < numThingsData; iThingsData2++ ) {
						thingsDataArr[iThingsData2] = thingsDataArr[iThingsData2].split(";");
						var id:int = thingsDataArr[iThingsData2][0];
						var xp:Point = new Point(thingsDataArr[iThingsData2][1], thingsDataArr[iThingsData2][2]);
						//map.putObstacle(id, xp);
					}
					break;
				default:
					break;
			}
		}

	}
}